//
// this is QQ-OpenAPI-V3 for golang porting, referenced from Python_SDK_V3
//

package qqopenapi_v3

import (
  "fmt"
  "net/url"
  "strconv"
  "time"
  . "github.com/ckrissun/go-simplejson"
)

const (
  OPEN_HTTP_TRANSLATE_ERROR = 1801
)

type OpenAPIV3 struct {
  _appid    int
  _appkey   string
  _api      *SNSNetwork
  _staturl  string
  _statapi  *SNSStat
  _is_stat  bool
}

func NewOpenAPIV3(appid int, appkey string, iplist *RandomString) *OpenAPIV3 {
  this := &OpenAPIV3{} 
  this._appid   = appid
  this._appkey  = appkey
  this._is_stat = true
  this._staturl = "apistat.tencentyun.com"

  seceret := this._appkey + "&"
  this._api = NewSNSNetwork(iplist, seceret, DEFAULT_SIG_NAME)
  this._statapi = NewSNSStat()
  return this
}

func (this *OpenAPIV3) SetIsStat(is_stat bool) {
  this._is_stat = is_stat
}

// 验证回调发货的签名
func (this *OpenAPIV3) VerifyPayCallbackSig(method, url_path string, params url.Values) bool {
  return verify_pay_callback_sig(this._appkey, method, url_path, params)
}

func (this *OpenAPIV3) Call(method, url_path, protocol string, params url.Values) *Json {
  params.Set("appid", strconv.Itoa(this._appid))
  params.Set("format", "json")

  var data *Json
  var err error
  var start_time = time.Now().Unix()

  data, err = this._api.open(method, url_path, protocol, params) 
  defer this.send_stat(method, url_path, protocol, data, start_time, params)
  if err != nil {
    data, _ = NewJson([]byte("{}"))
    data.Set("ret", OPEN_HTTP_TRANSLATE_ERROR)
    data.Set("msg", fmt.Sprintf("exception occur.msg[%v]", err))
  }
  return data
}

func (this *OpenAPIV3) send_stat(method, url_path, protocol string, result *Json, start_time int64, params url.Values) {
  if this._is_stat {
    // send stat
    var stat_param = make(map[string]interface{})
    stat_param["appid"]     = params.Get("appid")
    stat_param["pf"]        = params.Get("pf")
    stat_param["svr_name"]  = this._api._ipaddr
    stat_param["interface"] = url_path
    stat_param["protocol"]  = protocol
    stat_param["method"]    = method
    stat_param["rc"]        = result.Get("ret").MustInt(-123456)
    this._statapi.StatReport(this._staturl, start_time, stat_param)
  }
}

